﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Camc.Quality.StoreManagement.StoreInterface
{
    public class StoreHttp : IStoreHttp
    {
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public  string HttpPostData(string url, string postDataStr)
        {
            string strReturn;
            //在转换字节时指定编码格式
            byte[] byteData = Encoding.UTF8.GetBytes(postDataStr);
            //配置Http协议头
            HttpWebRequest resquest = (HttpWebRequest)WebRequest.Create(url);
            resquest.Method = "POST";
            resquest.ContentType = "application/json";
            resquest.Timeout = 9000;
            resquest.ContentLength = byteData.Length;
            //发送数据
            using (Stream resquestStream = resquest.GetRequestStream())
            {
                resquestStream.Write(byteData, 0, byteData.Length);
            }
            try 
            {
                //接受并解析信息
                using (WebResponse response = resquest.GetResponse())
                {
                    //解决乱码：utf-8 + streamreader.readToEnd
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                    strReturn = reader.ReadToEnd();
                    reader.Close();
                    reader.Dispose();
                }
            }
            catch (Exception ex)
            {
                strReturn = "";
            }
            return strReturn;
        }
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public string HttpGetData(string Url)
        {
            try
            {
                string retString = string.Empty;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "GET";
                request.ContentType = "application/xml";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(myResponseStream);
                retString = streamReader.ReadToEnd();
                streamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

    
    }
}
